package demo5;

import java.util.Arrays;

public class Sort {

    //归并排序
    public void mergeSort(int[] arr) {
        mergeFun(arr, 0, arr.length - 1);
    }

    private void mergeFun(int[] arr, int left, int right) {
        if(left >= right) {
            return;
        }
        int mid = (left + right) / 2;
        mergeFun(arr, left, mid);
        mergeFun(arr, mid + 1, right);
        //合并
        merge(arr, left, right, mid);
    }

    private void merge(int[] arr, int left, int right, int mid) {
        int[] tmpArr = new int[right - left + 1];
        int s1 = left;
        int s2 = mid + 1;
        int index = 0;
        while(s1 <= left && s2 <= right) {
            if(arr[s1] < arr[s2]) {
                tmpArr[index++] = arr[s1++];
            } else {
                tmpArr[index++] = arr[s2++];
            }
        }
        while(s1 <= mid) {
            tmpArr[index++] = arr[s1++];
        }
        while(s2 <= right) {
            tmpArr[index++] = arr[s2++];
        }
        for(int i = 0; i < index; i++) {
            arr[i + left] = tmpArr[i];
        }
    }

}

class Main {
    public static void main(String[] args) {
        int[] arr = {3,2,1,4,7,8,6,5,9};
        Sort sort = new Sort();
        sort.mergeSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}
